<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Athletes extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->lang->load('breadcrumb', 'estonian');
        $this->load->model('Athlete_model', 'AthleteModel');
        $this->load->library('pagination');
    }

    public function index() {

        redirect("athletes/show");
    }

    public function profile($id = false) {

        if ($id == false || !$this->AthleteModel->exists($id)) {
            redirect('athletes');
        } else {

            $data['top_five'] = $this->AthleteModel->fetchTopFiveResults($id);
            $data['athlete'] = $this->AthleteModel->fetch($id, true);
            $data['top_results'] = $this->AthleteModel->fetchTopResults($id);
            $this->load->template('profile', $data);
        }
    }

    public function search() {
        $fname = $this->input->post('fname');
        $lname = $this->input->post('lname');
        if (empty($fname) && empty($lname)) {
            redirect("athletes/show");
        }

        $query_array = array(
            'fname' => $fname,
            'lname' => $lname
        );

        $query_id = $this->input->save_query($query_array);

        redirect("athletes/show/$query_id");
    }

    public function show($query_id = 0, $offset = 0) {

        $this->input->load_query($query_id);
        $query_array = array(
            'fname' => $this->input->get('fname'),
            'lname' => $this->input->get('lname')
        );

        $config = array();
        $config['base_url'] = site_url("athletes/show/$query_id");

        $limit = 25;
        $data = $this->AthleteModel->search($query_array, true, $limit, $offset);
        // pagination

        $config['total_rows'] = $data['count'];
        $config['per_page'] = $limit;
        $config['uri_segment'] = 4;
        $config['first_link'] = 'Esimene';
        $config['last_link'] = 'Viimane';
        $config['full_tag_open'] = '<ul class="pagination">';
        $config['full_tag_close'] = '</ul>';
        $config['first_tag_open'] = '<li>';
        $config['first_tag_close'] = '</li>';
        $config['last_tag_open'] = '<li>';
        $config['last_tag_close'] = '</li>';
        $config['next_tag_open'] = '<li>';
        $config['next_tag_close'] = '</li>';
        $config['prev_tag_open'] = '<li>';
        $config['prev_tag_close'] = '</li>';
        $config['cur_tag_open'] = '<li class="active"><a>';
        $config['cur_tag_close'] = '</a></li>';
        $config['num_tag_open'] = '<li>';
        $config['num_tag_close'] = '</li>';
        $this->pagination->initialize($config);
        $data['pagination'] = $this->pagination->create_links();
        $data['offset'] = $offset;
        $this->load->template('athletes', $data);
    }

}